package com.dynamicapp.plugin

import android.content.Context
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.content.res.AssetManager
import android.content.res.Resources
import dalvik.system.DexClassLoader


class PluginManager private constructor() {
    var pluginDexClassLoader: DexClassLoader? = null
        private set
    var pluginResources: Resources? = null

    private var pluginPackageArchiveInfo: PackageInfo? = null

    fun loadApk(context: Context?, dexPath: String?) {
        dexPath ?: return

        if (pluginDexClassLoader == null) {
            pluginDexClassLoader = DexClassLoader(
                dexPath,
                context?.externalCacheDir?.absolutePath,
                null,
                context?.classLoader)
        }
    }

    fun getResourcesPackageInfo(context: Context?, dexPath: String?): PackageInfo? {
        dexPath ?: return null

        if (pluginResources == null) {
            var assets: AssetManager? = null
            try {
                assets = AssetManager::class.java.newInstance()
                val addAssetPath = AssetManager::class.java.getMethod("addAssetPath", String::class.java)
                addAssetPath.invoke(assets, dexPath)
            } catch (e: Exception) {
                e.printStackTrace()
            }
            pluginResources = Resources(assets, context?.resources?.displayMetrics, context?.resources?.configuration)
        }

        if (pluginPackageArchiveInfo == null) {
            pluginPackageArchiveInfo = context?.packageManager
                ?.getPackageArchiveInfo(dexPath, PackageManager.GET_ACTIVITIES)
        }
        return  pluginPackageArchiveInfo
    }

    companion object {
        val instance = PluginManager()
    }
}